import 'package:LifeMusic/components/iconText.dart';
import 'package:fluro/fluro.dart';
import 'package:LifeMusic/routers/application.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/phoenix_footer.dart';

import 'package:LifeMusic/model/sonListInfoModel.dart';
import 'package:LifeMusic/provider/musicPlayingProvider.dart';

import 'package:flutter_vant_kit/widgets/loading.dart';
import 'package:LifeMusic/api/songListApi.dart';
import 'package:provider/provider.dart';

class SongListPage extends StatefulWidget {
  final String listId;
  const SongListPage({Key key, this.listId}) : super(key: key);
  @override
  _SongListPageState createState() => _SongListPageState();
}

class _SongListPageState extends State<SongListPage> {
  // Map<String, dynamic> songInfoList = {};
  SongListModel songInfoList = SongListModel();
  List<dynamic> setSongInfoList = [];
  int mod = 0;
  int page = 0;
  int finalPage = 0;
  List songListIds = List();
  List loadSongListIds = List();
  Future getPlayList(id) async {
    var result = await SongApi.getPlayListDetail(id);
    return result;
  }

  Future _getSongList(ids) {
    return SongApi.getSongList(ids);
  }

  bool hasSongList = false;

  // 获取歌单详情
  _getPlayList() async {
    getPlayList(int.parse(widget.listId)).then((value) {
      Provider.of<PlayingStatus>(context, listen: false).playingList =
          value["playlist"]["tracks"];
      setState(() {
        setSongInfoList = value["playlist"]["tracks"];
        songInfoList = SongListModel.fromJson(value);
        for (var i = 0; i < songInfoList?.playlist?.trackIds?.length; i++) {
          songListIds.add(songInfoList?.playlist?.trackIds[i]?.id);
        }
      });
      print(songListIds);
      setState(() {
        mod = songListIds.length % 15;
        finalPage = songListIds.length ~/ 15;
        print('$mod');
        print('$finalPage');
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getPlayList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: setSongInfoList.length == 0
          ? Center(
              child: Loading(
                color: Colors.blueAccent,
                text: '正在努力加载中...',
              ),
            )
          : EasyRefresh(
              header: DeliveryHeader(),
              footer: PhoenixFooter(),
              onRefresh: () async {},
              onLoad: () async {
                await Future.delayed(Duration(seconds: 1), () {
                  if (mounted) {
                    setState(() {
                      if (page > finalPage) {
                        loadSongListIds =
                            songListIds.skip(page * 15).take(mod).toList();
                      } else {
                        int skipLength = songInfoList?.playlist?.tracks?.length;
                        if (finalPage == 0) {
                          loadSongListIds = songListIds
                              .skip(skipLength)
                              .take(songListIds.length - skipLength)
                              .toList();
                        } else {
                          if (page == 0) {
                            loadSongListIds = songListIds
                                .skip(skipLength)
                                .take((page + 1) * 15)
                                .toList();
                          } else {
                            loadSongListIds = songListIds
                                .skip(skipLength + page * 15)
                                .take((page + 1) * 15)
                                .toList();
                          }
                        }
                      }
                      if (loadSongListIds.isNotEmpty == false) return;
                      _getSongList(loadSongListIds.join(',')).then((value) {
                        Provider.of<PlayingStatus>(context, listen: false)
                            .playingList = value["songs"];
                        setSongInfoList.addAll(value["songs"]);
                        page++;
                      });
                    });
                  }
                });
              },
              child: CustomScrollView(
                slivers: <Widget>[
                  new SliverAppBar(
                      backgroundColor: Color.fromARGB(200, 64, 54, 60),
                      actions: <Widget>[
                        new IconButton(
                          icon: Icon(Icons.add),
                          onPressed: () {
                            print("添加");
                          },
                        ),
                        new IconButton(
                          icon: Icon(Icons.more_horiz),
                          onPressed: () {
                            print("更多");
                          },
                        ),
                      ],
                      title: Text("歌单"),
                      expandedHeight: 230.0,
                      floating: false,
                      pinned: true,
                      snap: false,
                      flexibleSpace: new FlexibleSpaceBar(
                        background: Container(
                          margin: EdgeInsets.fromLTRB(20, 60, 20, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                // margin: EdgeInsets.fromLTRB(15.0, 15.0, 10.0, 15.0),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(15),
                                    child: Container(
                                      width: 120,
                                      height: 150,
                                      child: FadeInImage.assetNetwork(
                                          placeholder: 'assets/rhomb-white.gif',
                                          image: songInfoList
                                              ?.playlist?.coverImgUrl ??
                                              '',
                                          fit: BoxFit.fill),
                                    ),)
                              ),
                              Container(
                                padding: EdgeInsets.only(left: 30),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text("${songInfoList?.playlist?.name}",style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white
                                    ),),
                                    Text("${songInfoList?.playlist?.creator?.nickname}"),
                                    Text("编辑歌单",style: TextStyle(
                                      fontWeight: FontWeight.bold
                                    ),),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      )),
                  new SliverFixedExtentList(
                    itemExtent: 65.0,
                    delegate: new SliverChildBuilderDelegate(
                      (context, index) => ListTile(
                        leading: Container(
                          height: 55,
                          width: 45,
                          child: Center(
                            child: Text("${index + 1}",
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 20)),
                          ),
                        ),
                        title: Text(setSongInfoList[index]["name"]),
                        subtitle: Text(
                          "${setSongInfoList[index]["ar"][0]["name"]}-${setSongInfoList[index]["al"]["name"]}",
                          style: TextStyle(fontSize: 10),
                          overflow: TextOverflow.ellipsis,
                        ),
                        trailing: IconButton(
                          icon: Icon(Icons.play_circle_outline),
                          onPressed: () {
                            Provider.of<PlayingStatus>(context, listen: false)
                                .musicIndex = index;
                            Application.router.navigateTo(context,
                                '/songPlayerPage?musicId=${setSongInfoList[index]["id"]}',
                                transition: TransitionType.fadeIn);
                          },
                        ),
                      ),
                      childCount: setSongInfoList?.length,
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}
